let host = 'https://www.5x4m.com';
let socketUrl = 'wss://www.5x4m.com/socket';
let lastUpdateTime = null;
let location = {};
let requestList = {} //api请求记录

let Api = {
    // 将当前请求的api记录起来
    addRequestKey: function (key) {
        requestList[key] = true
    },
    removeRequestKey: function removeRequestKey(key) {
        delete requestList[key]
    },
    //当前请求的api是否已有记录
    hitRequestKey: function hitRequestKey(key) {
        return requestList[key]
    },
    //根据请求的地址，请求参数组装成api请求的key,方便记录
    getRequestKey: function getRequestKey(url, method, data) {
        return 'method: ' + method + ',url: ' + url + ',data:' + JSON.stringify(data);
    },
    fetchApi: function (url, method, data) {
        let that = this;
        return new Promise((resolve, reject) => {
            let ajaxKey = that.getRequestKey(url, method, data)
            if (that.hitRequestKey(ajaxKey)) {
                return reject({message: '请求过于频繁'});
            } else {
                that.addRequestKey(ajaxKey)
                wx.request({
                    url: host + url,
                    method: method,
                    data: Object.assign({}, data),
                    header: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        'openId': null != getApp().globalData.userInfo ? getApp().globalData.userInfo.openId : null
                    },
                    complete: function (res) {
                        setTimeout(function () {
                            that.removeRequestKey(ajaxKey)
                        }, 500);
                        let statusCode = res.statusCode
                        if (statusCode === 200 || statusCode === 304) {
                            return resolve(res.data);
                        } else {
                            if (!statusCode) {
                                return reject({message: '网络异常'});
                            } else {
                                return reject({message: '请求异常'});
                            }
                        }
                    }
                })
            }
        })
    },

    get: function (url, data) {
        return this.fetchApi(url, 'GET', data).then(res => res)
    },

    post: function (url, data) {
        return this.fetchApi(url, 'POST', data).then(res => res)
    },

    put: function (url, data) {
        return this.fetchApi(url, 'PUT', data).then(res => res)
    },

    delete: function (url, data) {
        return this.fetchApi(url, 'DELETE', data).then(res => res)
    },

    getHost: function () {
        return host;
    },

    getSocketUrl: function (openId) {
        return socketUrl + '?' + openId;
    },

    getUserInfo: function () {
        let that = this;
        return new Promise((resolve, reject) => {
            //优先从全局变量获取用户信息
            if (null != getApp().globalData.userInfo) {
                return resolve(getApp().globalData.userInfo);
            } else {
                //次优从缓存获取用户信息
                wx.getStorage({
                    key: 'wuxuegai_userInfo',
                    success: function (res) {
                        let userInfo = res.data;
                        getApp().globalData.userInfo = userInfo;
                        return resolve(userInfo);
                    },
                    fail: function () {
                        wx.login({
                            success: function (res) {
                                let code = res.code;
                                that.get('/user/login/' + code).then(res => {
                                    let userInfo = res.data;
                                    if (userInfo.id) {
                                        getApp().globalData.userInfo = userInfo;
                                        that.setStorage('wuxuegai_userInfo', userInfo);
                                        return resolve(userInfo);
                                    } else {
                                        let newUserInfo = {};
                                        wx.getUserInfo({
                                            success: function (res) {
                                                let userData = JSON.parse(res.rawData);
                                                newUserInfo = {
                                                    nickname: userData.nickName,
                                                    avatarUrl: userData.avatarUrl,
                                                    gender: userData.gender == 0 ? 'FEMALE' : 'MALE'
                                                }
                                            },
                                            complete: function () {
                                                newUserInfo.openId = userInfo.openId;
                                                that.post('/user', newUserInfo).then(res => {
                                                    let userInfo = res.data;
                                                    getApp().globalData.userInfo = userInfo;
                                                    that.setStorage('wuxuegai_userInfo', userInfo);
                                                    return resolve(userInfo);
                                                }).catch((res) => {
                                                    return reject(res);
                                                });
                                            }
                                        });
                                    }
                                }).catch((res) => {
                                    return reject(res);
                                });
                            },
                            fail: function () {
                                return reject({message: '微信请求异常'});
                            }
                        });
                    }
                });
            }
        });
    },

    getLastLocation: function () {
        let that = this;
        return new Promise((resolve, reject) => {
            if (null != location) {
                return resolve(location);
            } else {
                that.getLocation().then((res) => {
                    location = res;
                    return resolve(res);
                }).catch((res) => {
                    return reject(res);
                });
            }
        });
    },

    getLastLocationLimit: function () {
        let that = this;
        return new Promise((resolve, reject) => {
            //限制一分钟获取一次位置信息
            if (null != lastUpdateTime && (lastUpdateTime.getTime() + 1000 * 60) > new Date().getTime()) {
                return resolve(location);
            } else {
                that.getLocation().then((res) => {
                    lastUpdateTime = new Date();
                    location = res;
                    return resolve(res);
                }).catch((res) => {
                    return reject(res);
                });
            }
        });
    },

    getLocation: function () {
        return new Promise((resolve, reject) => {
            wx.getLocation({
                success: function (res) {
                    let location = {
                        latitude: res.latitude,
                        longitude: res.longitude
                    }
                    return resolve(location);
                },
                fail: function () {
                    console.info('拒绝获取用户位置授权')
                    wx.showModal({
                        title: '温馨提示',
                        content: '您已拒绝获取用户位置，无法正常使用该功能',
                        confirmText: '重新授权',
                        cancelText: '确认',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        if (data && data.authSetting['scope.userLocation'] == true) {
                                            wx.getLocation({
                                                type: 'wgs84',
                                                success: function (res) {
                                                    let location = {
                                                        latitude: res.latitude,
                                                        longitude: res.longitude
                                                    }
                                                    return resolve(location);
                                                },
                                                fail: function () {
                                                    return reject({message: '获取用户位置失败，下拉重新获取'});
                                                }
                                            })
                                        } else {
                                            return reject({message: '您已拒绝获取位置授权，无法使用该功能'});
                                        }
                                    },
                                    fail: function () {
                                        return reject({message: '调用微信API失败，下拉重新获取'});
                                    }
                                });
                            } else {
                                return reject({message: '您已拒绝获取位置授权，无法使用该功能'});
                            }
                        }
                    });
                }
            })
        });
    },
    setStorage: function (key, value, sync) {
        if (!sync) {
            wx.setStorage({
                key: key,
                data: value
            })
        } else {
            try {
                wx.setStorageSync(key, value)
            } catch (e) {
                console.info('同步存储数据到缓存失败');
            }
        }
    },
    getStorage: function (key, sync) {
        if (!sync) {
            wx.getStorage({
                key: key,
                success: function (res) {
                    return res.data;
                },
                fail: function () {
                    return null;
                }
            })
        } else {
            try {
                return wx.getStorageSync(key);
            } catch (e) {
                return null;
            }
        }
    },
    removeStorage: function (key, sync) {
        if (!sync) {
            wx.removeStorage({key: key})
        } else {
            try {
                wx.removeStorageSync(key)
            } catch (e) {
                console.info('同步删除缓存失败');
            }
        }
    },
    showLoading: function (title) {
        wx.showLoading({title: title})
    },
    hideLoading: function () {
        setTimeout(function () {
            wx.hideLoading();
        }, 1000);
    },
    showToast: function (title) {
        wx.showToast({title: title, icon: 'success', duration: 2000});
    }
}

module.exports = Api;